﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Auditing;
using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Validation;

namespace Volo.Abp.Account.Public.Web.Pages.Account
{
	public class ResetPasswordModel : AccountPageModel
	{
		[HiddenInput]
		[BindProperty(SupportsGet = true)]
		public Guid? TenantId { get; set; }

		[BindProperty(SupportsGet = true)]
		[Required]
		[HiddenInput]
		public Guid UserId { get; set; }

		[Required]
		[BindProperty(SupportsGet = true)]
		[HiddenInput]
		public string ResetToken { get; set; }

		[DataType(DataType.Password)]
		[DynamicStringLength(typeof(IdentityUserConsts), "MaxPasswordLength", null)]
		[DisableAuditing]
		[BindProperty]
		[Required]
		public string Password { get; set; }

		[BindProperty]
		[DataType(DataType.Password)]
		[DynamicStringLength(typeof(IdentityUserConsts), "MaxPasswordLength", null)]
		[DisableAuditing]
		[Required]
		public string ConfirmPassword { get; set; }

		protected virtual ITenantResolveResultAccessor TenantResolveResultAccessor { get; }

		public ResetPasswordModel(ITenantResolveResultAccessor tenantResolveResultAccessor)
		{
			this.TenantResolveResultAccessor = tenantResolveResultAccessor;
		}

		public virtual Task<IActionResult> OnGetAsync()
		{
			this.CheckCurrentTenant(this.TenantId);
			return Task.FromResult<IActionResult>(this.Page());
		}

		public virtual async Task<IActionResult> OnPostAsync()
		{
			this.ValidateModel();
			try
			{
				await base.AccountAppService.ResetPasswordAsync(new ResetPasswordDto
				{
					UserId = this.UserId,
					ResetToken = this.ResetToken,
					Password = this.Password
				});
			}
			catch (AbpIdentityResultException ex)
			{
				if (string.IsNullOrWhiteSpace(ex.Message))
				{
					throw;
				}
				base.Alerts.Warning(ex.Message);
				return this.Page();
			}
			return this.RedirectToPage("./ResetPasswordConfirmation");
		}

		protected override void ValidateModel()
		{
			if (!object.Equals(this.Password, this.ConfirmPassword))
			{
				base.ModelState.AddModelError("ConfirmPassword", base.L["'{0}' and '{1}' do not match.", new object[]
				{
					"ConfirmPassword",
					"Password"
				}]);
			}
			base.ValidateModel();
		}
	}
}
